<template>
  <div>
    <ul class="imglist">
      <li v-for="(item, idx) in fileList" :key="idx" class="img-box">
        <img :src="item.src" alt="" @click="preview(idx)">
        <span class="rect-del" @click.stop="deleteImage(idx)"></span>
      </li>
    </ul>
    <el-upload ref="uploadPics" action="/api/uploadImage" accept="image/jpeg,image/gif,image/png" multiple list-type="picture-card" :before-upload="beforeUpload" :on-remove="handleRemove" :on-change="handleChange" :on-success="handleSuccess" :on-error="handleError" >
      <i class="el-icon-plus"></i>
    </el-upload>
    <!-- PhotoSwipe 官方空壳 -->
    <div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
      <div class="pswp__bg"></div>
      <div class="pswp__scroll-wrap">
        <div class="pswp__container">
          <div class="pswp__item"></div>
          <div class="pswp__item"></div>
          <div class="pswp__item"></div>
        </div>
        <div class="pswp__ui pswp__ui--hidden">
          <div class="pswp__top-bar">
            <div class="pswp__counter"></div>
            <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
// import PhotoSwipe from 'photoswipe/dist/photoswipe'
// eslint-disable-next-line camelcase
// import PhotoSwipeUI_Default from 'photoswipe/dist/photoswipe-ui-default'
import 'photoswipe/dist/photoswipe.css'
import 'photoswipe/dist/default-skin/default-skin.css'
export default {
  props: [ ],
  data: function () {
    return {
      imgQuality: 0.5,
      imgs: [
        {
          url: '',
          title: '',
          preview: '1'
        }
      ],
      imgList: [],
      fileList: [],
      pswp: null
    }
  },
  methods: {
    getImageIds () {
      return this.imgList
    },
    setImageList (imglist, imgids) {
      this.imgList = imgids
      this.fileList = []
      if (imglist) {
        imglist.forEach((item) => {
          this.fileList.push({id: item.id, src: item.url})
        })
      }
      this.$refs.uploadPics.clearFiles()
      // this.fileList = imgList
      // this.$previewRefresh()
    },
    preview (index = 0) {
      this.$imagePreview({
        images: this.fileList.map(item => item.src),
        index: index
      })
      /* const items = this.imgList.map(src => ({ src, w: 0, h: 0 }))
      const options = {
        index,
        history: false,
        focus: false,
        closeEl: true,
        shareEl: false,
        fullscreenEl: false
      }

      // 必须找到官方空壳 .pswp
      const pswpElement = document.querySelector('.pswp')

      this.pswp = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options)

      // 4. 监听打开完成 → 插删除按钮
      this.pswp.listen('initialZoomInEnd', () => this.injectDeleteBtn())
      this.pswp.listen('afterChange', () => this.injectDeleteBtn())

      this.pswp.init() */
    },

    /* 5. 动态插删除按钮 */
    injectDeleteBtn () {
      if (!this.pswp) return
      let btn = document.querySelector('.pswp__delete-btn')
      if (btn) return // 已经插过

      btn = document.createElement('button')
      btn.className = 'pswp__button pswp__delete-btn'
      btn.title = '删除这张图片'
      btn.innerHTML = '🗑️'
      btn.style.cssText = `
        position:absolute;top:10px;right:50px;
        background:rgba(0,0,0,.5);color:#fff;border:none;
        padding:4px 8px;border-radius:4px;font-size:18px;cursor:pointer;z-index:9999;`
      btn.onclick = () => this.onDelete()
      this.pswp.container.appendChild(btn)
    },

    /* 6. 删除逻辑 */
    onDelete () {
      const _this = this
      if (!_this.pswp) return
      const idx = _this.pswp.getCurrentIndex()
      _this.$confirm('确定删除这张图片吗？', '提示', { type: 'warning' })
        .then(() => {
          _this.fileList.splice(idx, 1) // 同步外部数组
          _this.pswp.close() // 关闭预览
        })
        .catch(() => {})
    },

    /* 7. 普通缩略图上的删除 */
    deleteImage (idx) {
      const _this = this
      _this.$confirm('确定删除？', '提示', { type: 'warning' })
        .then(() => {
          var items = _this.fileList.splice(idx, 1)
          var id = items[0].id
          for (let i = _this.imgList.length - 1; i >= 0; i--) {
            if (_this.imgList[i] === id) {
              _this.imgList.splice(i, 1)
            }
          }
        })

      /* this.$imagePreview({
        images: this.fileList,
        index: index
      }) */
    },
    dataURItoBlob (dataURI, type) {
      var binary = atob(dataURI.split(',')[1])
      var array = []
      for (var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i))
      }
      return new Blob([new Uint8Array(array)], {type: type})
    },
    beforeUpload (param) {
      // 对图片进行压缩
      const imgSize = param.size / 1024 / 1024
      if (imgSize > 1) {
        const _this = this
        return new Promise(resolve => {
          const reader = new FileReader()
          const image = new Image()
          image.onload = (imageEvent) => {
            const canvas = document.createElement('canvas')
            const context = canvas.getContext('2d')
            const width = image.width * _this.imgQuality
            const height = image.height * _this.imgQuality
            canvas.width = width
            canvas.height = height
            context.clearRect(0, 0, width, height)
            context.drawImage(image, 0, 0, width, height)
            const dataUrl = canvas.toDataURL(param.type)
            const blobData = _this.dataURItoBlob(dataUrl, param.type)
            resolve(blobData)
          }
          reader.onload = e => { image.src = e.target.result }
          reader.readAsDataURL(param)
        })
      } else {
        return new Promise(resolve => {
          const reader = new FileReader()
          const image = new Image()
          image.onload = (imageEvent) => {
            // const width = image.width
            // const height = image.height
            // _this.imgWidthHeight = `${width}/${height}`
            // console.log(`图片上传前，不需要压缩：${_this.imgWidthHeight}`)
            resolve()
          }
          reader.onload = e => { image.src = e.target.result }
          reader.readAsDataURL(param)
        })
      }
    },
    // 处理图片预览效果
    handlePreview (file) {
      this.previewPath = file.url
      this.previewVisible = true
    },
    // 处理移除图片的操作
    handleRemove (file) {
      //* 1. 获取将要删除的图片的临时路径
      var id = file.response.data.id
      for (let i = this.imgList.length - 1; i >= 0; i--) {
        if (this.imgList[i] === id) {
          this.imgList.splice(i, 1)
        }
      }
    },
    handleChange (file, fileList) {
      this.imgNum = fileList.length
      const el = document.getElementsByClassName('el-upload')[0]
      if (fileList.length >= this.limit - 0) {
        el.style.display = 'none'
      }
    },
    handleSuccess (res, file, fileList) {
      this.imgList.push(file.response.data.id)
      this.$notify.success({
        title: '成功',
        message: `文件上传成功`
      })
    },
    // 文件上传失败时的钩子
    handleError (err, file, fileList) {
      console.log(err)
      console.log(file)
      console.log(fileList)
      this.$notify.error({
        title: '错误',
        message: `文件上传失败`
      })
    }
  }
}
</script>
<style>
@import "../assets/css/global.css";
img {
  width: 145px;
  height: 145px;
  padding: 0 5px;
}
.imglist {
  text-align: left;
}

.imglist > li {
  display: inline;
}
.thumb{display:flex;flex-wrap:wrap}
.thumb .item{position:relative;margin:4px}
.thumb img{width:120px;height:90px;object-fit:cover}
.thumb .del{
  position:absolute;top:2px;right:2px;
  background:rgba(0,0,0,.6);color:#fff;
  border-radius:50%;width:20px;height:20px;
  text-align:center;line-height:20px;cursor:pointer
}

.my-upload .el-upload-list--picture-card .el-upload-list__item-actions .el-upload-list__item-delete {
  opacity: 1 !important;
}

.img-box {
  position: relative;   /* 1. 基准 */
  display: inline-block; /* 让 li 包住图片 */
}

.del {
  position: absolute;   /* 2. 脱离文档流 */
  right: 22px;           /* 3. 贴右下角 */
  bottom: 22px;
  cursor: pointer;
  border-radius: 50%;
  width: 42px;
  height: 42px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36px;
  color: #ff0000;
}
.rect-del{
  display:inline-block;
  width:30px; height:8px;          /* 长方形尺寸 */
  background:#ff0000; border-radius:1px;
  vertical-align:middle; cursor:pointer;
  position: absolute;   /* 2. 脱离文档流 */
  right: 28px;           /* 3. 贴右下角 */
  bottom: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ff0000;
}
</style>
